<template>
  <view class="max_box">
    <view class="head_box">
      <view class="user_box">
        <view class="photo_box" @click="openUpdateModal">
          <image class="photo" :src="loginInfo.avatarUrl"></image>
        </view>
        <view class="icon-xian icon-position" @click="openUpdateModal">
          <uni-icons custom-prefix="iconfont2" type="icon-xiangji" color="#eee" size="28rpx"></uni-icons>
        </view>
        <view class="name_box">
          <view @click="openUpdateModal" class="name_box__text">{{ loginInfo.nickName }}</view>
          <view class="name_box__tips">
            <view class="name_box__tips__cp" v-if="couponByPhone.length > 0">已绑会员卡</view>
            <view class="name_box__tips__cp red" v-if="couponByPhone.length > 0" @click="goCoupon">{{ couponNum }}劵</view>
            <view class="name_box__tips__cp black" v-else @click="goCoupon">点击绑定会员卡</view>
          </view>
        </view>
      </view>
      <view class="btn_box">
        <view class="btn" @click="openPopup">
          <uni-icons type="help" size="56rpx"></uni-icons>
        </view>
        <view class="btn" @click="goContact">
          <uni-icons type="headphones" size="56rpx"></uni-icons>
        </view>
      </view>
    </view>
    <!-- <view class="maix_box">
      <view class="serve_box order_box">
        <view class="top_box">
          <view class="title">我的订单</view>
          <view class="all_box" @click="toOrderDetail(0)">
            <view class="all">查看全部</view>
            <uni-icons type="right" size="28rpx" color="#999"></uni-icons>
          </view>
        </view>
        <view class="nav_box">
          <view :key="item.state" class="nav_item_box" v-for="(item, index) in infoList"
            @click.stop="toOrderDetail(item.state)">
            <view :class="['t-icon', item.icon]"></view>
            <view class="font">{{ item.title }}</view>
            <view class="info" v-if="index === 2 && goodsTipsCount > 0">{{
              goodsTipsCount
            }}</view>
            <view class="info" v-if="index === 1 && noPayCount > 0">{{
              noPayCount
            }}</view>
          </view>
        </view>
        <view class="new_logistics_box">
          <template v-if="hasInfo">
            <view class="new_logistics">
              <view class="logistics_title">最新物流</view>
              <view class="date">{{ logisticsInfo.info[0].date }}</view>
            </view>
            <view class="logistics_box" @click="showModal = true">
              <view class="img">
                <image class="img" mode="aspectFill" :src="`${baseUrl}/images/audi/library/${logisticsInfo.img}`"></image>
              </view>
              <view class="logistics">[ {{ logisticsInfo.info[0].position }} ]
                {{ logisticsInfo.info[0].state }}</view>
            </view>
          </template>
          <view class="logistics_box" v-else> 暂无最新物流信息!</view>
        </view>
      </view>
    </view> -->
    <view class="maix_box">
      <view class="serve_box">
        <view class="title">我的服务</view>
        <view class="nav_box">
          <view class="item_nav" :key="item.id" v-for="item in serveList" @click.stop="toDetailPage(item.url)">
            <view :class="['t-icon', item.icon]"></view>
            <view class="text">{{ item.title }}</view>
          </view>
          <!-- 退出登录 -->
          <view class="item_nav" @click="logOut()">
            <view class="t-icon t-icon-tuichu"></view>
            <view class="text">退出登录</view>
          </view>
        </view>
      </view>
    </view>
    <!-- 弹窗 -->
    <uni-popup ref="popup" type="bottom" :mask-click="false" background-color="#f6f6f6" @maskClick="closePopup">
      <!-- 电话 -->
      <view class="content_box">
        <view class="content_box__title">联系我们</view>
        <scroll-view scroll-y="true" class="scroll_view" :scroll-top="scrollTop">
          <view class="box">
            <view :key="item.id" class="photo_no" :class="{ borBtm: index > 0 }" v-for="(item, index) in centers"
              @click="phoneCall(item.hotline)">
              <text class="name">{{ item.value }}</text>
              <text class="text">{{ item.hotline }}</text>
            </view>
          </view>
        </scroll-view>
      </view>
    </uni-popup>
    <!-- 物流信息 -->
    <u-modal :show="showModal" title="物流信息" @confirm="showModal = false" confirmColor="#de4141">
      <view class="slot-content">
        <scroll-view scroll-y="true" class="scroll-Y">
          <u-steps current="1" direction="column" activeColor="#de4141" :dot="true">
            <u-steps-item :key="index" :title="item.state" :desc="item.date + ' - ' + item.time"
              v-for="(item, index) in logisticsInfo.info">
            </u-steps-item>
          </u-steps>
        </scroll-view>
      </view>
    </u-modal>
    <!-- 修改昵称头像 -->
    <u-popup closeable :round="12" :show="showUpdateModal" @close="closeUpdateModal">
      <view class="update-info">
        <view class="update-info__title">编辑用户和昵称 </view>
        <button class="avatar-wrapper" open-type="chooseAvatar" @chooseavatar="onChooseAvatar">
          <image class="avatar" :src="avatarUrl"></image>
        </button>
        <view class="icon-xian icon-position">
          <uni-icons custom-prefix="iconfont2" type="icon-xiangji" color="#eee" size="28rpx"></uni-icons>
        </view>
        <!-- @input="bindinput"  -->
        <input v-model="nickname" class="nickname" type="nickname" placeholder="编辑昵称" />
        <view class="update-info__btn" @click="saveInfoUpdate">保 存 </view>
      </view>
    </u-popup>
  </view>
</template>
<script>
const dayjs = require('dayjs')
// 是七天以内的?
let isSevenDayBefore = function (data) {
  let date1 = new Date(data).getTime() + 7 * 3600 * 24 * 1000
  let time = dayjs(date1).format('YYYY-MM-DD')
  return dayjs().isBefore(dayjs(time))
}

import { mapState, mapMutations } from 'vuex'
import { userUpdateApi } from '@/API/userLogin'
import { infoList, serveList } from '@/static/js/staticData'
import { goodsOrderListApi, fastPieceApi, couponByPhoneApi } from '@/API/Shop'

let logisticsInfo = []
let flag = 0
export default {
  name: 'MyInfo',
  props: {},
  data() {
    return {
      nickname: '',
      avatarUrl: '',
      avataraName: '',
      updateParam: {
        uuid: '',
        brand: '',
        nickName: '',
        avatarUrl: '',
      },
      showUpdateModal: false,
      goodsTipsCount: 0,
      noPayCount: 0,
      baseUrl: this.$baseUrl,
      showModal: false,
      infoList,
      serveList,
      index: 0,
      // goodsOrderList: [],
      logisticsInfo: {},
      queryParam: {
        state: 1,
        brand_id: '',
        page: 1,
        pageSize: 20,
        // uuid:''
      }
    }
  },
  mounted() {
    let { uuid, nickName, avatarUrl, avataraName } = this.loginInfo
    let { brand, brand_id } = this.brandInfo
    this.queryParam.uuid = uuid
    this.queryParam.brand_id = brand_id
    this.updateParam.uuid = uuid
    this.updateParam.brand = brand
    this.nickname = nickName
    this.avatarUrl = avatarUrl
    this.avataraName = avataraName
    this.getGoodsOrderList()
    this.getCouponByPhone(brand_id)
  },
  methods: {
    ...mapMutations(['saveLoginInfo', 'saveCouponByPhone']),
    async onChooseAvatar(e) {
      const { avatarUrl } = e.detail
      uni.uploadFile({
        url: `${this.baseUrl}/wx/uploadAvatarImg`, //后端接口
        filePath: avatarUrl,
        name: 'file',
        header: "post",
        success: (res) => {
          let { code, message, path } = JSON.parse(res.data)
          if (code == 200) {
            this.avatarUrl = `${this.baseUrl}/images/avatar/${path}`
            this.avataraName = path
            console.log('path', path);
          }
        },
        fail: (e) => {
          console.log('e', e);
        }
      })
    },
    openUpdateModal() {
      this.showUpdateModal = true
      uni.hideTabBar()
    },
    closeUpdateModal() {
      this.showUpdateModal = false
      uni.showTabBar()
    },
    async saveInfoUpdate() {
      let avataraName = this.avataraName
      this.updateParam.nickName = this.nickname
      this.updateParam.avatarUrl = avataraName
      const { data: { code, message } } = await userUpdateApi(this.updateParam)
      if (code == 200) {
        uni.$showMsg(`${message}`)
        let loginInfo = this.loginInfo
        loginInfo.nickName = this.nickname
        loginInfo.avatarUrl = `${this.baseUrl}/images/avatar/${avataraName}`
        loginInfo.avataraName = avataraName
        this.saveLoginInfo(loginInfo)
        this.closeUpdateModal()
      }
    },
    // 优惠券列表
    async getCouponByPhone(brand_id) {
      const {
        data: { data, code }
      } = await couponByPhoneApi({
        phone: this.loginInfo?.phoneNumber,
        brand_id: brand_id
      })
      this.saveCouponByPhone(data)
      // this.couponByPhone = data

      console.log('-', this.couponByPhone)
    },
    // 订单列表
    async getGoodsOrderList() {
      const {
        data: { data, goodsTipsCount, noPayCount }
      } = await goodsOrderListApi(this.queryParam)
      this.noPayCount = noPayCount
      this.goodsTipsCount = goodsTipsCount
      // 过滤出需要发货，并有快递单的
      let orderList = data.filter(
        item =>
          item.goodsInfo.post_service < 3 &&
          item.logistics_no &&
          item.logistics_no.length > 8
      )
      // 查询物流信息
      for (let index = 0; index < orderList.length; index++) {
        this.queryPostInfo(
          orderList[index].logistics_no,
          orderList.length,
          orderList[index].goodsInfo.images_kv
        )
      }
    },
    // 查快递信息
    async queryPostInfo(No, len, img) {
      // let param = { waybillNo: 'SF1148970949236' }
      let param = { waybillNo: `SF${No}` }
      const { data } = await fastPieceApi(param)
      // 请求成功
      if (data.apiResultData.success) {
        // console.log(data)
        // console.log(data.apiResultData.obj.route[0])
        // 所有的物流信息
        let temp = { info: data.apiResultData.obj.route, img }
        // console.log('temp',temp);
        logisticsInfo.push(temp)
      }

      flag++
      if (flag === len) {
        this.getNewLogistics()
      }
    },
    getNewLogistics() {
      // 最新的物流信息
      let temp = logisticsInfo.sort(function (a, b) {
        return a?.info?.[0]?.date < b?.info?.[0]?.date ? 1 : -1
      })[0]

      //  opCode为80,应该是"已签收"
      if (temp?.info?.[0]?.opCode == 80) {
        // 判断是否七天以内的
        // let isflag = isSevenDayBefore('2023-02-20')
        let isflag = isSevenDayBefore(temp.info[0].date)
        if (isflag) {
          // console.log('temp', isflag)
          this.logisticsInfo = temp
        }
        // 未签收
      } else {
        this.logisticsInfo = temp
      }
    },
    // 打电话
    phoneCall(e) {
      uni.makePhoneCall({ phoneNumber: `${e}` })
    },
    // 帮助
    openPopup() {
      this.$refs.popup.open()
      uni.hideTabBar()
    },
    // 客服列表
    goContact() {
      uni.navigateTo({
        url: `/pages/Service/ServiceList`
      })
    },
    // 关闭联系人
    closePopup() {
      this.$refs.popup.close()
      uni.showTabBar()
    },
    toDetailPage(url) {
      // console.log(url)
      uni.navigateTo({
        url: `${url}`
      })
    },
    toOrderDetail(state) {
      uni.navigateTo({
        url: `/Shop/OrderAdmin?state=${state}`
      })
    },
    goCoupon() {
      uni.navigateTo({ url: `/Shop/CouponList` })
    },
    goCardsReg() {
      uni.navigateTo({ url: `/Shop/CardsReg` })
    },
    logOut() {
      uni.showModal({
        title: '提示',
        content: '你确定要退出登录吗？',
        success: res => {
          if (res.confirm) {
            // 清空缓存
            // uni.clearStorageSync()
            uni.removeStorageSync('loginInfo');
            // uni.removeStorageSync('address');
            // 清空vuex的信息
            this.saveLoginInfo({})
          } else if (res.cancel) {
            uni.showToast({
              title: '你取消了退出',
              icon: 'none'
            })
          }
        }
      })
    }
  },
  computed: {
    ...mapState(['loginInfo', 'centers', 'brandInfo', 'couponByPhone']),
    // 有物流信息？
    hasInfo() {
      if (this.logisticsInfo?.info?.length > 0) {
        return true
      }
      return false
    },
    couponNum() {
      if (this.loginInfo?.phoneNumber?.length > 0) {
        let num = 0
        this.couponByPhone.forEach(
          item => (num = num + item.couponRelations.length)
        )
        return num
      }
      return false
    }
  }
}
</script>
<style lang="scss">
@import '../../static/css/iconfont-weapp-icon.css';

page {
  background-color: #fafafa;
}
</style>
<style lang="scss" scoped>
@import '@/styles/mixins.scss';

.max_box {
  padding-top: 136rpx;
  background-image: linear-gradient(145deg,
      #ffe4e4,
      #ffe7e19c,
      #fafafa,
      #fafafa,
      #fafafa) !important;

  .icon-xian {
    width: 35rpx;
    height: 35rpx;
    border-radius: 50%;
    background-color: rgba(0, 0, 0, 0.6);
    display: flex;
    justify-content: center;
    align-items: center;
    z-index: 9999;
  }

  .head_box {
    margin: 0 auto;
    display: flex;
    justify-content: space-between;
    align-items: center;
    width: 90%;
    height: 270rpx;


    .user_box {
      // width: 600rpx;
      display: flex;
      align-items: center;
      position: relative;

      .photo_box {
        z-index: 3;
        width: 134rpx;
        height: 134rpx;
        border-radius: 50%;
        border: 1px solid #eee;
        overflow: hidden;
        box-shadow: $theme-shadow;
        background-color: #fff;

        .photo {
          width: 100%;
          height: 100%;
        }
      }

      .icon-position {
        position: absolute;
        bottom: 4rpx;
        left: 92rpx;
      }



      .name_box {
        padding-left: 20rpx;
        display: flex;
        flex-direction: column;
        z-index: 3;

        .name_box__text {
          font-size: 32rpx;
          font-weight: 600;
        }

        .name_box__tips {
          margin-top: 10rpx;
          display: flex;
          flex-direction: row;
          font-size: 24rpx;
          color: #a9a9a9;

          .name_box__tips__cp {
            margin-right: 10rpx;
            padding: 5rpx 12rpx;
            background: #fbfcfb;
            border: 1rpx solid #e0e0e0;
            border-radius: 100rpx;

            &.red {
              color: $theme-color;
            }

            &.black {
              color: #000;
            }
          }
        }
      }
    }

    .btn_box {
      width: 140rpx;
      display: flex;
      justify-content: space-between;

      .btn {
        width: 65rpx;
        height: 65rpx;
        border-radius: 50%;
        display: flex;
        justify-content: center;
        align-items: center;
      }
    }
  }

  .maix_box {
    border-radius: 12rpx;
    padding-bottom: 30rpx;

    .order_box {
      padding-bottom: 30rpx;
    }

    .serve_box {
      width: 90%;
      margin: 0 auto;
      background-color: #fff;
      border-radius: 12rpx;
      box-shadow: $theme-shadow2;

      .title {
        padding: 26rpx 0 0 30rpx;
        line-height: 68rpx;
        font-size: 32rpx;
        color: #333;
        font-weight: 600;
      }

      .top_box {
        display: flex;
        align-items: center;
        justify-content: space-between;

        .all_box {
          display: flex;
          align-items: baseline;
          padding: 26rpx 30rpx 0 0rpx;

          .all {
            font-size: 26rpx;
            color: #999;
          }
        }
      }

      .nav_box {
        padding: 4rpx 0 10rpx;
        display: flex;
        flex-wrap: wrap;

        .nav_item_box {
          padding: 24rpx 0 0rpx;
          width: 25%;
          margin: 0;
          text-align: center;
          position: relative;

          .font {
            line-height: 36rpx;
            font-size: 22rpx;
            color: #666;
          }

          .info {
            width: 30rpx;
            border-radius: 50%;
            line-height: 30rpx;
            position: absolute;
            top: 0;
            right: 34rpx;
            text-align: center;
            font-size: 18rpx;
            background-color: $theme-color;
            color: #fafafa;
          }
        }

        .item_nav {
          padding: 24rpx 0 26rpx;
          width: 33.33%;
          margin: 0;
          text-align: center;

          .iconfont {
            color: un;
          }

          .text {
            line-height: 60rpx;
            font-size: 30rpx;
            color: #333;
          }
        }
      }
    }

    .new_logistics_box {
      background-color: #f5f6fb;
      margin: 10rpx 30rpx;
      border-radius: 8rpx;
      padding: 10rpx 25rpx 20rpx 25rpx;

      .new_logistics {
        margin-bottom: 20rpx;
        display: flex;
        align-items: center;
        justify-content: space-between;

        .logistics_title {
          font-size: 26rpx;
        }

        .date {
          font-size: 22rpx;
        }
      }

      .logistics_box {
        display: flex;
        align-items: center;
        text-align: center;
        justify-content: center;
        font-size: 24rpx;
        color: $theme-color;

        .img {
          width: 80rpx;
          height: 80rpx;
          border-radius: 8rpx;
          overflow: hidden;
        }

        .logistics {
          flex: 1;
          height: 70rpx;
          font-size: 26rpx;
          margin-left: 20rpx;
          text-align: left;
          color: #666;
          @include text-ellipsis(2);
        }
      }
    }
  }
}

// 电话
.content_box {
  background-color: #f6f6f6;

  &__title {
    text-align: center;
    line-height: 86rpx;
    font-size: 30rpx;
    background-color: #fff;
    border-bottom: 1px solid #eee;
  }

  .box {
    background-color: #fff;
    padding: 30rpx 30rpx 45rpx 30rpx;

    .photo_no {
      text-align: center;

      .name {
        line-height: 108rpx;
      }

      .text {
        display: inline-block;
        padding: 0 10rpx;
        line-height: 108rpx;
        font-size: 28rpx;
        color: $theme-color;
      }
    }

    .borBtm {
      border-top: 1px solid #eee;
    }
  }

  .scroll_view {
    height: 40vh;
  }
}

.scroll-Y {
  height: 60vh;
}

::v-deep ::-webkit-scrollbar {
  /*滚动条整体样式*/
  width: 5px !important;
  height: 3px !important;
  overflow: auto !important;
  background: #ccc !important;
  -webkit-appearance: auto !important;
  display: block;
}

::v-deep ::-webkit-scrollbar-thumb {
  /*滚动条里面小方块*/
  border: 5px solid #747272 !important;
  border-radius: 10px !important;
  box-shadow: inset 0 0 10px rgba(0, 0, 0, 0.1) !important;
  background: #7b7979 !important;
}

::v-deep ::-webkit-scrollbar-track {
  /*滚动条里面轨道*/
  // box-shadow: inset 0 0 5px rgba(0, 0, 0, 0.2) !important;
  // border-radius: 10px !important;
  background: #ffffff !important;
}

.t-icon-mywx5 {
  // width: 90% !important;
  background-repeat: no-repeat;
  background-size: contain;
  background-position: center center;
  // widows: 100% !important;
}

.update-info {
  padding: 50rpx 30rpx 30rpx 30rpx;
  position: relative;

  &__title {
    font-size: 38rpx;
    font-weight: 600;
    text-align: center;
  }

  .icon-position {
    position: absolute;
    top: 230rpx;
    right: 295rpx;
  }

  // 头像
  .avatar-wrapper {
    width: 140rpx;
    height: 140rpx;
    margin: 50rpx auto;
    padding: 0;
    border-radius: 50%;
    background-color: #fff;
    border: #ddd solid 1px;

    .avatar {
      width: 100%;
      height: 100%;
    }
  }

  .nickname {
    width: 70%;
    margin: 0 auto;
    height: 80rpx;
    text-align: center;
    border-radius: 40rpx;
    line-height: 80rpx;
    padding: 0 20rpx;
    background-color: #f7f7f7;
    color: #222;
  }

  &__btn {
    width: 70%;
    margin: 40rpx auto;
    font-size: 32rpx;
    line-height: 80rpx;
    border-radius: 40rpx;
    color: #fafafa;
    text-align: center;
    background-color: $theme-color;
  }
}
</style>
